package solution._0130._0130;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by chen_snow
 * Date: 2021/6/30 21:47
 * Description: 被围绕的区域
 */
public class Solution {
    public void solve(char[][] board) {
        if (board.length == 1 || board[0].length == 1) {
            return;
        }

        Queue<int[]> oList = findEdgeO(board);

        while (!oList.isEmpty()) {
            int size = oList.size();
            for (int i = 0; i < size; i++) {
                int[] peer = oList.poll();
                oList.addAll(find(peer, board));
            }
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] = board[i][j] == 'Y' ? 'O' : 'X';
            }
        }


    }

    public List<int[]> find(int[] peer, char[][] board) {
        List<int[]> result = new ArrayList<>();
        int row = peer[0];
        int column = peer[1];
        if (row - 1 >= 0 && board[row - 1][column] == 'O') {
            result.add(new int[]{row - 1, column});
            board[row - 1][column] = 'Y';
        }

        if (row + 1 < board.length && board[row + 1][column] == 'O') {
            result.add(new int[]{row + 1, column});
            board[row + 1][column] = 'Y';
        }

        if (column - 1 >= 0 && board[row][column - 1] == 'O') {
            result.add(new int[]{row, column - 1});
            board[row][column - 1] = 'Y';
        }

        if (column + 1 < board[0].length && board[row][column + 1] == 'O') {
            result.add(new int[]{row, column + 1});
            board[row][column + 1] = 'Y';
        }

        return result;
    }


    public Queue<int[]> findEdgeO(char[][] board) {
        Queue<int[]> result = new LinkedList<>();
        int row = board.length - 1;
        int column = board[0].length - 1;
        for (int i = 0; i < board[0].length; i++) {
            if (board[0][i] == 'O') {
                result.offer(new int[]{0, i});
                board[0][i] = 'Y';
            }

            if (board[row][i] == 'O') {
                result.offer(new int[]{row, i});
                board[row][i] = 'Y';
            }
        }

        for (int i = 1; i < board.length - 1; i++) {
            if (board[i][0] == 'O') {
                result.offer(new int[]{i, 0});
                board[i][0] = 'Y';
            }

            if (board[i][column] == 'O') {
                result.offer(new int[]{i, column});
                board[i][column] = 'Y';
            }
        }
        return result;
    }
}
